import { Controller } from 'egg';

export default class HomeController extends Controller {
  public async index() {
    // const { ctx } = this;
    // // ctx.body = await ctx.service.test.sayHi('egg');
    // await ctx.render('login.ejs');


    const { ctx } = this;

    if (ctx.isAuthenticated()) {
      ctx.body = `<div>
        <h2>${ctx.path}</h2>
        <hr>
        Logined user: <img src="${ctx.user.photo}"> ${ctx.user.displayName} / ${ctx.user.id} | <a href="/logout">Logout</a>
        <pre><code>${JSON.stringify(ctx.user, null, 2)}</code></pre>
        <hr>
        <a href="/">Home</a> | <a href="/user">User</a>
      </div>`;
    } else {
      ctx.session.returnTo = ctx.path;
      ctx.body = `
        <div>
          <h2>${ctx.path}</h2>
          <hr>
          <form action="/add" method="post">
            <input type="hidden" name="_csrf" value="${ctx.csrf}">
            用户名：<input type="text" name="username" /><br/>
            密 码：<input type="password" name="password" /><br/>
            <button type="submit">登录</button>
          </form>
          Login with
          <a href="/passport/weibo">Weibo</a>
          <hr>
          <a href="/">Home</a> | <a href="/user">User</a>
        </div>
      `;
    }
  }

  public async add() {
    const { ctx, app } = this;
    ctx.cookies.set('username', ctx.request.body.username);
    const token = app.jwt.sign({
      username: ctx.request.body.username,
      password: ctx.request.body.password,
    }, app.config.jwt.secret);
    ctx.set({ authorization: token });
    ctx.body = token;
  }
}
